<template>
  <d2-container>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    v-on:close="onClose"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio v-for="(type, index) in dataForm.typeList" :label="index" :key="index">{{ type }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="dataForm.typeList[dataForm.type] + '名称'" prop="title">
        <el-input v-model="dataForm.title" :placeholder="dataForm.typeList[dataForm.type] + '名称'"></el-input>
      </el-form-item>
      <el-form-item label="上级菜单" prop="parentName">
        <el-popover
          ref="menuListPopover"
          placement="bottom-start"
          trigger="click">
          <el-tree
            :data="menuList"
            :props="menuListTreeProps"
            node-key="menuId"
            ref="menuListTree"
            @current-change="menuListTreeCurrentChangeHandle"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName" v-popover:menuListPopover :readonly="true" placeholder="点击选择上级菜单" class="menu-list__input"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 1" label="路由地址" prop="path">
        <el-input v-model="dataForm.path" placeholder="菜单路由URL"></el-input>
      </el-form-item>
      <el-form-item label="授权标识" prop="perms">
        <el-input v-model="dataForm.perms" placeholder="多个用逗号分隔, 如: user:list,p_user_create"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== 2" label="排序号" prop="orderNum">
        <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序号"></el-input-number>
      </el-form-item>
      <el-form-item label="是否锁定" prop="isLock">
        <el-switch
            v-model="dataForm.isLock">
        </el-switch>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== 2" label="菜单图标">
        <el-row>
          <el-col :span="22">
            <d2-icon-select v-model="dataForm.icon" :user-input="true"/>
          </el-col>
          <el-col :span="2" class="icon-list__tips">
            <el-tooltip placement="top" effect="light">
              <div slot="content">请选择图标</div>
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="对该菜单（权限）的备注"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
  </d2-container>
</template>

<script>
import util from '@/libs/util.js'
import * as service from '@api/userperm.api.fetch'
export default {
  name: 'menu-add-or-update',
  data () {
    var validateUrl = (rule, value, callback) => {
      if (this.dataForm.type === 1 && !/\S/.test(value)) {
        callback(new Error('菜单URL不能为空'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      dataForm: {
        id: 0,
        type: 1,
        typeList: ['目录', '菜单'],
        title: '',
        parentId: 0,
        parentName: '',
        path: '',
        perms: '',
        orderNum: 0,
        isLock: false,
        icon: '',
        remark: '',
        uuid: ''
      },
      dataRule: {
        title: [
          { required: true, message: '菜单名称不能为空', trigger: 'blur' }
        ],
        parentName: [
          { required: true, message: '上级菜单不能为空', trigger: 'change' }
        ],
        path: [
          { validator: validateUrl, trigger: 'blur' }
        ]
      },
      menuList: [],
      menuListTreeProps: {
        label: 'title',
        children: 'children'
      }
    }
  },
  mounted () {
    this.uuid = util.cookies.get('uuid')
  },
  methods: {
    init (id) {
      this.dataForm.id = id || 0
      service.reqTree().then(res => {
        this.menuList = res.data
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (!this.dataForm.id) {
          // 新增
          this.menuListTreeSetCurrentNode()
        } else {
          // 修改
          service.reqInfo(this.dataForm.id).then(res => {
            let data = res.data
            this.dataForm.id = data.menuId
            this.dataForm.type = data.type
            this.dataForm.title = data.title
            this.dataForm.parentId = data.parentId
            this.dataForm.path = data.path
            this.dataForm.perms = data.perms
            this.dataForm.isLock = data.isLock
            this.dataForm.orderNum = data.orderNum
            this.dataForm.icon = data.icon
            this.dataForm.parentName = data.parentName
            this.dataForm.remark = data.remark
            this.menuListTreeSetCurrentNode()
          })
        }
      })
    },
    // 菜单树选中
    menuListTreeCurrentChangeHandle (data, node) {
      this.dataForm.parentId = data.menuId
      this.dataForm.parentName = data.title
    },
    // 菜单树设置当前选中节点
    menuListTreeSetCurrentNode () {
      this.$refs.menuListTree.setCurrentKey(this.dataForm.parentId || this.menuList[0].menuId)
      this.dataForm.parentName = this.dataForm.parentName || this.menuList[0].title
      // this.dataForm.parentName = (this.$refs.menuListTree.getCurrentNode() || {})['title']
    },
    onClose () {
      this.visible = false
      this.$emit('refreshDataList')
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var postData = {
            'menuId': this.dataForm.id || undefined,
            'type': this.dataForm.type,
            'title': this.dataForm.title,
            'parentId': this.dataForm.parentId,
            'path': this.dataForm.path,
            'perms': this.dataForm.perms,
            'orderNum': this.dataForm.orderNum,
            'icon': this.dataForm.icon,
            'isLock': this.dataForm.isLock
          }
          var mAction = postData.menuId ? service.reqUpdate : service.reqSave
          mAction(postData).then(res => {
            this.$message({
              message: '操作成功，若要看到菜单栏的改变按F5请刷新页面',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$router.push('menu')
              }
            })
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
  .mod-menu {
    .menu-list__input,
    .icon-list__input {
       > .el-input__inner {
        cursor: pointer;
      }
    }
    &__icon-popover {
      width: 458px;
      overflow: hidden;
    }
    &__icon-inner {
      width: 478px;
      max-height: 258px;
      overflow-x: hidden;
      overflow-y: auto;
    }
    &__icon-list {
      width: 458px;
      padding: 0;
      margin: -8px 0 0 -8px;
      > .el-button {
        padding: 8px;
        margin: 8px 0 0 8px;
        > span {
          display: inline-block;
          vertical-align: middle;
          width: 18px;
          height: 18px;
          font-size: 18px;
        }
      }
    }
    .icon-list__tips {
      font-size: 18px;
      text-align: center;
      color: #e6a23c;
      cursor: pointer;
    }
  }
</style>
